class DomInViewObserver {
    constructor(obj) {
        this._io = null;
        this.$setting = obj;
        this.$active = null;

        this.init();
    }

    init() {
        var {el, handler} = this.$setting;

        this._io = new IntersectionObserver(e => {
            var res = [...e].filter(item => {
                return item.isIntersecting;
            }).map(item => {
                var {target, isIntersecting, intersectionRatio} = item;

                return {
                    id: target.id,
                    isIntersecting,
                    intersectionRatio,
                };
            });

            if (!res.length) {
                return;
            }

            if (!this.$active) {
                // 首屏渲染完毕，取第一个

                this.$active = res[0];
            } else {
                this.$active = res[res.length - 1];
            }

            handler && handler(this.$active.id);
        });

        if (typeof el === 'string') {
            this.$targets = document.querySelectorAll(el);
        } else {
            this.$targets = el;
        }

        this.$targets.forEach(el => {
            this._io.observe(el);
        });
    }

    destroy() {
        this._io.disconnect();
        this._io = null;
    }
}

export default DomInViewObserver;